<?php
namespace Apps\Weixin\Services;


use Apps\Common\Constant\BusinessConstant;
use Apps\Common\Constant\CacheKeyConstant;
use Apps\Common\Constant\CacheTimeoutConstant;
use Apps\Weixin\Models\WxConfig;
use Deyi\Functions\CacheFunction;
use Deyi\Functions\ObjectFunction;

class WxConfigService extends WxConfig
{
    protected static $_cache = [];

    public function getConfigByService($service, $updCache = false)
    {
        $res = [];

        if (isset(static::$_cache[$service]) && (RUN_MODE == 'WEB') && !$updCache) {
            $res = static::$_cache[$service];
        }

        if (!$res) {
            $cacheKey = CacheFunction::generateKey(CacheKeyConstant::WX_CONFIG_DATA_CACHE_KEY, $service);

            $res = $updCache ? false : static::$_memcached->get($cacheKey);

            if (!is_array($res)) {
                $funcName = __FUNCTION__ . '_' . $service;
                // 5次取锁机会
                $retry = 5;
                $res = [];
                while ($this->serviceTransactionLock($funcName, 2) && (--$retry >= 0)) {
                    $tmp = $this->getConfigDataByService($service);
                    foreach ($tmp as $v) {
                        $res[$v->id] = ObjectFunction::toArray($v);;
                    }
                    static::$_memcached->set($cacheKey, $res, CacheTimeoutConstant::LOCAL_MAX_CACHE);
                    $this->serviceTransactionUnLock($funcName);
                    break;
                }
            }
        }

        $data = [];
        foreach ($res as $k => $v) {
                $data[$v['attrcode']] = $v;
        }

        return static::$_cache[$service] = $data;
    }

    public function getTrade()
    {
        $config = $this->getConfigByService(BusinessConstant::SERVICE_SPECIFY_CODE);

        $trade = [];
        foreach ($config as $key => $value) {
            if (($temp_key = str_replace("trading_", "", $key)) != $key) {
                $info = explode(',',$temp_key);
                $trade[] = [
                    'from' => $info[0],
                    'to'=> $info[1],
                    'award'=>$value['attrval']
                ];
            }
        }
        return $trade;
    }

    public function getViewPrice()
    {
        $config = $this->getConfigByService(BusinessConstant::SERVICE_SPECIFY_CODE);

        $views = [];
        foreach ($config as $key => $value) {
            if (($temp_key = str_replace("view_", "", $key)) != $key) {
                $info = explode(',',$temp_key);
                $views[$info[1]] = $value['attrval'];
            }
        }
        return $views;
    }

}